var express = require('express');
var router = express.Router();
//导入
const low = require('lowdb');
const shortid=require('shortid');
const FileSync = require('lowdb/adapters/FileSync')
 
const adapter = new FileSync(__dirname+'/../data/db.json')
//获取db对象;
const db = low(adapter);

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
router.get('/bills', function(req, res, next) {
  let posts=db.get('posts').value();
  console.log(posts);
  res.render('bills',{posts:posts});
});
router.get('/bills/create', function(req, res, next) {
  res.render('create');
});
router.post('/bills', function(req, res, next) {
  let id=shortid.generate();
  db.get('posts').unshift({id:id,...req.body}).write();
  console.log(req.body);
  res.render('success',{msg:'添加成功',url:'/bills'});
});

router.get('/bills/:id',(req,res)=>{
  let id=req.params.id;
  db.get('posts').remove({id:id}).write();
  res.render('success',{msg:'删除成功',url:'/bills'});
});


module.exports = router;
